﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AIMLbot;
using System.IO;
using Styx.Common;
using System.Threading;

namespace ShutUp_AIML
{
    public partial class AnswerTestForm : Form
    {
        public AnswerTestForm()
        {
            InitializeComponent();
        }

        private Bot myBot;
        private User myUser;
        private bool _working = false;
        public static Queue<ChatMessage> answerQueue = new Queue<ChatMessage>();
        private List<string> DefaultMesg = new List<string>();
        private readonly Random _rand = new Random(DateTime.Now.Millisecond);

        public void slog(string message, params object[] args)
        { Logging.Write(System.Windows.Media.Colors.Aqua, "[ShutUp - AIML][Test]: " + message, args); }

        private void AnswerTestForm_Load(object sender, EventArgs e)
        {
            myBot = new Bot();
            myUser = new User("bot2", myBot);
            loadAIML(PathToAIML);
        }

        /// <summary>
        /// The directory to look in for the AIML files
        /// </summary>
        public string PathToAIML
        {
            get
            {
                return Path.Combine(Application.StartupPath, "Plugins\\ShutUpAIML\\LanguageFiles\\c_aiml"); //TODO CHANGE FOLDER
            }
        }

        /// <summary>
        /// Loads the AIML from files found in the path
        /// </summary>
        /// <param name="path"></param>
        public void loadAIML(string path)
        {
            if (Directory.Exists(path))
            {
                // process the AIML
                string[] fileEntries = Directory.GetFiles(path, "*.aiml");
                if (fileEntries.Length > 0)
                {
                    lbox_aiml_Files.Items.Clear();
                    foreach (string filename in fileEntries)
                    {
                        try
                        {
                            slog("load AIML files: " + filename);
                            lbox_aiml_Files.Items.Add(filename.Replace(path, "").Remove(0,1));
                        }
                        catch (Exception ex)
                        { Logging.WriteException(ex); }
                    }
                }
                else
                {
                    slog("Could not find any .aiml files in the specified directory (" + path + "). Please make sure that your aiml file end in a lowercase aiml extension, for example - myFile.aiml is valid but myFile.AIML is not.");
                }
            }
            else
            {
                slog("The directory specified as the path to the AIML files (" + path + ") cannot be found by the AIMLLoader object. Please make sure the directory where you think the AIML files are to be found is the same as the directory specified in the settings file.");
            }
        }

        private void richTextBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button1_Click(null, null);
            }
        }

        private void richTextBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (e.KeyChar == (char)Keys.Enter)
            //{
            //    richTextBox2.Text = string.Empty;
            //}
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ChatMessage m = new ChatMessage(richTextBox2.Text, "ME", "", "");
            richTextBox1.AppendText("[" + DateTime.Now.ToLongTimeString() + "] [ME]: " + richTextBox2.Text + "\n");
            richTextBox1.ScrollToCaret();
            if (_working)
            {
                slog("add to queue: " + richTextBox2.Text);
                answerQueue.Enqueue(m);
            }
            else
                handleMessage(m);

            richTextBox2.Text = string.Empty;
        }

        private void handleMessage(ChatMessage e)
        {
            slog("handleMessage: " + e.message);
            _working = true;
            string returnMessage = string.Empty;
            try
            {
                Request r = new Request(e.message, myUser, myBot);
                Result res = myBot.Chat(r);
                Thread.Sleep(101);
                returnMessage = res.Output;

                if (string.IsNullOrEmpty(returnMessage))
                {
                    returnMessage = "[AIML - no answer found] [Random answer";

                    if (ShutUpGlobalSettings.Instance.randomAnswer == null || ShutUpGlobalSettings.Instance.randomAnswer.ToList().Count <= 0)
                    {
                        returnMessage += " - no answer found] ";
                    }
                    else
                    {
                        returnMessage += "]: " + ShutUpGlobalSettings.Instance.randomAnswer[_rand.Next(0, DefaultMesg.Count())].ToString();
                    }
                }

                if (returnMessage.Contains("dontedit_namespacer")) returnMessage = returnMessage.Replace("dontedit_namespacer", e.Author);
                if (returnMessage.Contains("Unknown")) returnMessage = returnMessage.Replace("Unknown", "...");

                slog("returnMessage: " + returnMessage);
                richTextBox1.AppendText("[" + DateTime.Now.ToLongTimeString() + "] " + "[AIMLBot]: " + returnMessage + "\n");
                richTextBox1.ScrollToCaret();
            }
            catch (Exception ex)
            { slog(ex.ToString()); }
            finally
            {
                if (answerQueue.Count > 0) { handleMessage(answerQueue.Dequeue()); }
                _working = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            AnswerTestForm_Load(null, null);
        }
    }
}
